<template>
    <z-page>
        <view class="h-full overflow-x-hidden overflow-y-scroll">
            <LoginCheck
                v-if="loadingStatusRef === LoadingStatus.ready"
                :has-debug="hasDebug"
                @did-toggle-debug="toggleDebugAction"
                @did2-open-debugger="openDebuggerAction"
                @did2-auth-page="toAuthPageAction"
            ></LoginCheck>
        </view>
    </z-page>
</template>
<script lang="ts" setup>
import { ref } from "vue";
import { DBKey } from "@/const";
import { AppNotificationEnum } from "@/event/globalNotification/eventSource/const";
import { emitNotification } from "@/event";
import { useAppStore } from "@/store";
import { asyncUniAPIWrap } from "@/utils/apiWrap";
import { dbManger } from "@/utils/db/dbManger";
import { feedback } from "@/helper";
import { uniOnLoad } from "@/utils/lifeCycle";
import { getAppBaseInfo, setEnableDebug, router } from "@/helper";
import LoginCheck from "./components/loginCheck.vue";
import { addToast2Queue } from "@/utils/toastQueue";
import { Useful, toString } from "utils";
import { API_User_Login } from "../../api";
import { useRequest } from "@/utils/network/request";
import type { AppUser } from "@/typings/app";
// 请求
const { APIRequest } = useRequest();
const appStore = useAppStore();

const enum LoadingStatus {
    ready = 0,
    loading = 1,
    fai = 2,
}

let { enableDebug } = getAppBaseInfo();
const hasDebug = ref(enableDebug);
uniOnLoad({
    needLogin: false,
    cb() {
        // #ifdef MP-WEIXIN
        // 隐藏 小房子 按钮
        asyncUniAPIWrap("hideHomeButton", {});
        // #endif
    },
});

const toggleDebugAction = () => {};
const openDebuggerAction = () => {
    // 打开调试
    setEnableDebug({
        enableDebug: true,
        success() {
            hasDebug.value = true;
        },
    });
};

const toAuthPageAction = () => {
    router.navigateTo({
        url: "/views/main/login/auth/controller/auth",
        events: {
            didGetAuth: function (info: { code: string | undefined }) {
                let { code } = info || {};
                startLogin(code);
            },
        },
    });
};

const loadingStatusRef = ref<LoadingStatus>(LoadingStatus.ready);
// 开始登录
async function startLogin(code: string | undefined) {
    if (!Useful.string(code)) {
        addToast2Queue("授权码无效");
        return;
    }
    loadingStatusRef.value = LoadingStatus.loading;
    feedback.showLoading({ title: "登录中...", mask: true });
    let [err, data] = await APIRequest(API_User_Login({ code: code || "" })).run();
    if (!!err) {
        loadingStatusRef.value = LoadingStatus.fai;
        return;
    }
    feedback.hideLoading();
    // 2个内存  local 一份,  store一份
    let appUser = data as AppUser;
    appStore.updateAppUser(appUser);
    dbManger.save({ _type: "sync", key: DBKey.user, value: toString(appUser) });
    // 跳转首页
    emitNotification(AppNotificationEnum.login);
}
</script>
<style lang="scss" scoped></style>
